package com.hys.ultrasound.base.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hys.ultrasound.BaseApplication;
import com.hys.ultrasound.R;
import com.hys.ultrasound.base.event.EventCode;
import com.hys.ultrasound.base.interfaces.BaseInterface;
import com.hys.ultrasound.base.mvp.Err;
import com.hys.ultrasound.base.mvp.MvpBaseView;
import com.lpjeremy.libmodule.event.MessageEvent;
import com.lpjeremy.uimodule.dialog.ProgressDialog;
import com.lpjeremy.uimodule.loadingstate.LoadingStateView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;


/**
 * @desc:所有activity基类
 * @date:2019/1/29 9:49
 * @auther:lp
 * @version:1.0
 */
public abstract class BaseActivity extends AppCompatActivity implements BaseInterface, MvpBaseView {
    protected Context mContext;
    protected Handler mHandler = new Handler(Looper.getMainLooper());

    protected BaseApplication mApplication;
    public ProgressDialog mProgressDialog;
    private FrameLayout mRootView;
    protected LoadingStateView mLoadingStateView;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseInit();
    }

    private void baseInit() {
        mContext = this;
        mApplication = (BaseApplication) getApplication();
        mApplication.addActivity(this);
        initRootView();
        setContentView(mRootView);
        ButterKnife.bind(this);
        init();
    }

    private void initRootView() {
//        View toolbarView = LayoutInflater.from(mContext).inflate(R.layout.layout_toolbar, null);
//        Toolbar toolbar = toolbarView.findViewById(R.id.toolBar);
//        toolbar.setTitle(getTitle().toString());
//        setSupportActionBar(toolbar);

        mRootView = new FrameLayout(mContext);
        mRootView.addView(LayoutInflater.from(mContext).inflate(getLayoutResId(), null));
        mLoadingStateView = (LoadingStateView) LayoutInflater.from(mContext).inflate(R.layout.layout_loading_state_view, null);
        mRootView.addView(mLoadingStateView);
    }

    private void init() {
        register();
        initView();
        initData();
    }


    private void register() {
        if (registerEventBus()) {
            EventBus.getDefault().register(this);
        }
    }

    /**
     * 初始化view
     */
    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 得到布局id
     *
     * @return
     */
    protected abstract int getLayoutResId();

    /**
     * 是否注册eventbus
     *
     * @return
     */
    protected boolean registerEventBus() {
        return EventBus.getDefault().isRegistered(this);
    }


    @Override
    public void showToast(String toast) {
        if (!TextUtils.isEmpty(toast)) {
            ToastUtils.showShort(toast);
        }
    }

    @Override
    public void showToast(int resId) {
        if (resId > 0) {
            ToastUtils.showShort(resId);
        }
    }

    protected void post(Runnable runnable) {
        if (mHandler != null && runnable != null)
            mHandler.post(runnable);
    }

    public void startActivity(Class clazz) {
        if (mContext != null)
            startActivity(new Intent(mContext, clazz));
    }

    public void startActivityForResult(Class clazz, int request) {
        if (mContext != null)
            BaseActivity.this.startActivityForResult(new Intent(mContext, clazz), request);
    }

    public void startActivity(Class clazz, Intent intent) {
        if (mContext != null)
            intent.setClass(mContext, clazz);
        startActivity(intent);
    }

    @Override
    protected void onPause() {
        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(), 0);
        super.onPause();
    }

    /**
     * 显示数据加载中progressbar
     */
    public void showLoadingProgressBar() {
        showProgressBar(getString(R.string.data_loading));
    }

    /**
     * 显示“操作中...”progressbar
     */
    public void showOperationProgressBar() {
        showProgressBar(getString(R.string.operation_toast));
    }

    public void showProgressBar(final String toast) {
        if (isFinishing()) return;
        if (mProgressDialog == null)
            mProgressDialog = new ProgressDialog(mContext);
        if (!mProgressDialog.isShowing()) {
            post(new Runnable() {
                @Override
                public void run() {
                    mProgressDialog.showProgressBar(toast);
                }
            });

        } else {
            mProgressDialog.setmTxtProgressValue(toast);
        }
    }

    public void hideProgressBar() {
        post(new Runnable() {
            @Override
            public void run() {
                if (mProgressDialog != null && mProgressDialog.isShowing())
                    mProgressDialog.dismiss();
            }
        });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackClick();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    protected void onBackClick() {
        finish();
    }


    /**
     * 接受eventBus发送的消息的方法
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusMessage(MessageEvent event) {
        LogUtils.e("收到消息" + event.getCode());
        if (event.getCode() == EventCode.NETWORK_ERROR) {
            showToast("网络异常！！！");
            return;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (registerEventBus())
            EventBus.getDefault().unregister(this);
    }

    @Override
    public void showLoading(CharSequence toast) {
        if (toast != null) {
            showProgressBar(toast.toString());
        }
    }

    @Override
    public void showLoading() {
        showLoadingProgressBar();
    }

    @Override
    public void showOperationLoading() {
        showOperationProgressBar();
    }

    @Override
    public void hideLoading() {
        hideProgressBar();
    }

    @Override
    public void onError(Err err) {
        showToast(err.getErrMsg());
    }

    @Override
    public void noAttachedView() {
        showToast("未绑定当前view");
    }

    @Override
    public void showCheckToast(String toast) {
        showToast(toast);
    }

    @Override
    public void showCheckToast(int toastId) {
        showToast(toastId);
    }

    /**
     * 获取焦点
     *
     * @param editText
     */
    protected void requestFocus(final EditText editText) {
        if (editText == null) {
            return;
        }
        editText.postDelayed(new Runnable() {
            @Override
            public void run() {
                editText.requestFocus();
            }
        }, 200);
    }
}
